﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ExifLibrary;
using System.Text.RegularExpressions;

namespace MediaBeschrijver
{
    public partial class MediaOverzicht : Form
    {
        public MediaOverzicht()
        {
            InitializeComponent();
        }
        private void MediaOverzicht_Load(object sender, EventArgs e)
        {
            ReadSectionValues();
            LoadDirectory();
        }

        private void ReadSectionValues()
        {
            try
            {
                textBoxBaseDir.Text = ConfigurationManager.AppSettings["defaultDirectory"];
                Application.DoEvents();
            }
            catch (Exception exc)
            {
                statusBar.Text = exc.Message;
            }
        }

        #region curFile
        private string _curFileName;
        public string curFileName
        {
            get
            {
                return _curFileName;
            }
            set
            {
                _curFileName = value;
            }
        }
        #endregion

        #region ImageInfo
        public struct ImageInfo
        {
            private string _type;
            public string Type
            {
                get
                {
                    return _type;
                }
                set
                {
                    if (value != null)
                        _type = value;
                    else
                        _type = "";
                }
            }

            private string _titel;
            public string Titel
            {
                get
                {
                    return _titel;
                }
                set
                {
                    if (value != null)
                        _titel = value;
                    else
                        _titel = "";
                }
            }
            private string _description;
            public string Description
            {
                get
                {
                    return _description;
                }
                set
                {
                    if (value != null)
                        _description = value;
                    else
                        _description = "";
                }
            }
            private string _lokatie;
            public string Lokatie
            {
                get
                {
                    return _lokatie;
                }
                set
                {
                    if (value != null)
                        _lokatie = value;
                    else
                        _lokatie = ""; ;
                }
            }
            private DateTime _datum;
            public DateTime Datum
            {
                get
                {
                    return _datum;
                }
                set
                {
                    if (value == null)
                        _datum = Convert.ToDateTime("01-01-1900");
                    else
                        _datum = value;
                }
            }
            private string _vervaardiger;
            public string Vervaardiger
            {
                get
                {
                    return _vervaardiger;
                }
                set
                {
                    if (value != null)
                        _vervaardiger = value;
                    else
                        _vervaardiger = "";
                }
            }
            private string _archiefnummer;
            public string Archiefnummer
            {
                get
                {
                    return _archiefnummer;
                }
                set
                {
                    if (value != null)
                        _archiefnummer = value;
                    else
                        _archiefnummer = "";
                }
            }
            private string _subnummer;
            public string Subnummer
            {
                get
                {
                    return _subnummer;
                }
                set
                {
                    if (value != null)
                        _subnummer = value;
                    else
                        _subnummer = "";
                }
            }
            private string _mapnummer;
            public string Mapnummer
            {
                get
                {
                    return _mapnummer;
                }
                set
                {
                    if (value != null)
                        _mapnummer = value;
                    else
                        _mapnummer = "";
                }
            }
            private string _collectie;
            public string Collectie
            {
                get
                {
                    return _collectie;
                }
                set
                {
                    if (value != null)
                        _collectie = value;
                    else
                        _collectie = "";
                }
            }
            private string _montage;
            public string Montage
            {
                get
                {
                    return _montage;
                }
                set
                {
                    if (value != null)
                        _montage = value;
                    else
                        _montage = "";
                }
            }
            private string _techniek;
            public string Techniek
            {
                get
                {
                    return _techniek;
                }
                set
                {
                    if (value != null)
                        _techniek = value;
                    else
                        _techniek = "";
                }
            }
            private string _rivierengebied;
            public string Rivierengebied
            {
                get
                {
                    return _rivierengebied;
                }
                set
                {
                    if (value != null)
                        _rivierengebied = value;
                    else
                        _rivierengebied = "";
                }
            }
            private string _provincie;
            public string Provincie
            {
                get
                {
                    return _provincie;
                }
                set
                {
                    if (value != null)
                        _provincie = value;
                    else
                        _provincie = "";
                }
            }
            private string _project;
            public string Project
            {
                get
                {
                    return _project;
                }
                set
                {
                    if (value != null)
                        _project = value;
                    else
                        _project = "";
                }
            }
        }
        #endregion

        private int rowindex = -1;

        private void openDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectDirectory_Click(sender, e);
            LoadDirectory();
        }

        private void LoadDirectory()
        {
            string selPath = textBoxBaseDir.Text;

            try
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("Naam");
                dt.Columns.Add("Filenaam");

                string[] directoryList = System.IO.Directory.GetFiles(selPath, "*.jpg");
                foreach (string imageFile in directoryList)
                {
                    try
                    {
                        System.Data.DataRow dr = dt.NewRow();
                        dr["Naam"] = imageFile.Substring(imageFile.LastIndexOf("\\") + 1, imageFile.Length - imageFile.LastIndexOf("\\") - 1);
                        dr["Filenaam"] = imageFile;
                        dt.Rows.Add(dr);
                    }
                    catch (Exception exc)
                    {
                        statusBar.Text = "Inlezen - " + imageFile + "-" + exc.Message;
                    }
                }
                directoryList = System.IO.Directory.GetFiles(selPath, "*.tif");
                foreach (string imageFile in directoryList)
                {
                    try
                    {
                        System.Data.DataRow dr = dt.NewRow();
                        dr["Naam"] = imageFile.Substring(imageFile.LastIndexOf("\\") + 1, imageFile.Length - imageFile.LastIndexOf("\\") - 1);
                        dr["Filenaam"] = imageFile;
                        dt.Rows.Add(dr);
                    }
                    catch (Exception exc)
                    {
                        statusBar.Text = "Inlezen - " + imageFile + "-" + exc.Message;
                    }
                }
                directoryList = System.IO.Directory.GetFiles(selPath, "*.tiff");
                foreach (string imageFile in directoryList)
                {
                    try
                    {
                        System.Data.DataRow dr = dt.NewRow();
                        dr["Naam"] = imageFile.Substring(imageFile.LastIndexOf("\\") + 1, imageFile.Length - imageFile.LastIndexOf("\\") - 1);
                        dr["Filenaam"] = imageFile;
                        dt.Rows.Add(dr);
                    }
                    catch (Exception exc)
                    {
                        statusBar.Text = "Inlezen - " + imageFile + "-" + exc.Message;
                    }
                }

                dataGridViewImages.DataSource = dt;
                dataGridViewImages.Columns[0].Width = dataGridViewImages.Width/2;
                dataGridViewImages.Columns[1].Width = dataGridViewImages.Width/2;
            }
            catch (Exception exc)
            {
                statusBar.Text = "Inlezen - " + exc.Message;
            }

            if (dataGridViewImages.RowCount > 0)
                rowindex = 0;
            else
                rowindex = -1;

            FetchRow();

            tabMediaBeschrijver.SelectTab(0);
        }

        private void ResetFields()
        {
            textBoxTitel.BackColor = Color.LavenderBlush;
            textBoxOmschrijving.BackColor = Color.LavenderBlush;
            textBoxArchiefnummer.BackColor = Color.LavenderBlush;
            textBoxSubnummer.BackColor = Color.LavenderBlush;
            textBoxMapnummer.BackColor = Color.LavenderBlush;
            textBoxCollectie.BackColor = Color.LavenderBlush;
            textBoxLokatie.BackColor = Color.LavenderBlush;
            textBoxVervaardiger.BackColor = Color.LavenderBlush;

            cboProject.BackColor = Color.LavenderBlush;
            cboProvincie.BackColor = Color.LavenderBlush;
            cboRivierengebied.BackColor = Color.LavenderBlush;
            cboTechniek.BackColor = Color.LavenderBlush;

            buttonExifDatum.Enabled = false;
            buttonExifOmschrijving.Enabled = false;
            buttonExifTitel.Enabled = false;

            pictureBoxImage.Image = null;
            dataGridViewMetaData.DataSource = null;

            btnToolbarSave.Enabled = false;
            btnToolbarSaveAndNext.Enabled = false;
            btnToolbarSaveAll.Enabled = false;
            btnToolbarDeleteAll.Enabled = false;

            bewaarMetadataToolStripMenuItem.Enabled = false;
            bewaarEnVolgendeToolStripMenuItem.Enabled = false;
            kopieerNaarAlleBeeldenToolStripMenuItem.Enabled = false;
            verwijderAlleMetadataToolStripMenuItem.Enabled = false;
        }

        private void FetchRow()
        {
            ResetFields();

            if (rowindex > -1)
            {
                curFileName = dataGridViewImages.Rows[rowindex].Cells["Filenaam"].Value.ToString();
                if (File.Exists(curFileName))
                {
                    // Display the source file
                    pictureBoxImage.Image = Image.FromFile(curFileName);
                    textBoxTitel.Text = curFileName.Substring(curFileName.LastIndexOf("\\") + 1, curFileName.LastIndexOf(".") - curFileName.LastIndexOf("\\") - 1);

                    TryToSetArchiveAndSubNr(textBoxTitel.Text);

                    GetMetaData(curFileName);
                    btnToolbarSave.Enabled = true;
                    btnToolbarSaveAndNext.Enabled = true;
                    btnToolbarSaveAll.Enabled = true;
                    btnToolbarDeleteAll.Enabled = true;

                    bewaarMetadataToolStripMenuItem.Enabled = true;
                    bewaarEnVolgendeToolStripMenuItem.Enabled = true;
                    kopieerNaarAlleBeeldenToolStripMenuItem.Enabled = true;
                    verwijderAlleMetadataToolStripMenuItem.Enabled = true;
                }

                // Fetch XML data
                ImageInfo curImageInfo = LoadXml(curFileName);

                // Fill XML data in formfields
                // Check if values are present
                if (curImageInfo.Type != "Leeg")
                {
                    comboBoxObjectType.SelectedItem = curImageInfo.Type;
                    ShowTypeTab();

                    if (curImageInfo.Titel.Length > 0)
                    {
                        textBoxTitel.Text = curImageInfo.Titel;
                        textBoxTitel.BackColor = Color.LightGreen;
                    }
                    if (curImageInfo.Description.Length > 0)
                    {
                        textBoxOmschrijving.Text = curImageInfo.Description;
                        textBoxOmschrijving.BackColor = Color.LightGreen;
                    }
                    if (curImageInfo.Datum > DateTime.MinValue)
                    {
                        dateTimePickerDatum.Text = curImageInfo.Datum.ToString();
                    }
                    else
                    {
                        if (GetImageDate(pictureBoxImage.Image).HasValue)
                        {
                            dateTimePickerDatum.Text = GetImageDate(pictureBoxImage.Image).ToString();
                        }
                        else
                        {
                            dateTimePickerDatum.Text = DateTime.Today.ToString();
                        }
                    }
                    textBoxArchiefnummer.Text = curImageInfo.Archiefnummer;
                    textBoxArchiefnummer.BackColor = Color.LightGreen;
                    textBoxSubnummer.Text = curImageInfo.Subnummer;
                    textBoxSubnummer.BackColor = Color.LightGreen;
                    textBoxMapnummer.Text = curImageInfo.Mapnummer;
                    textBoxMapnummer.BackColor = Color.LightGreen;
                    comboBoxMontage.SelectedItem = curImageInfo.Montage;
                    textBoxCollectie.Text = curImageInfo.Collectie;
                    textBoxCollectie.BackColor = Color.LightGreen;
                    textBoxLokatie.Text = curImageInfo.Lokatie;
                    textBoxLokatie.BackColor = Color.LightGreen;
                    textBoxVervaardiger.Text = curImageInfo.Vervaardiger;
                    textBoxVervaardiger.BackColor = Color.LightGreen;
                    cboProject.BackColor = Color.LightGreen;
                    cboProject.Text = curImageInfo.Project;
                    cboProvincie.BackColor = Color.LightGreen;
                    cboProvincie.Text = curImageInfo.Provincie;
                    cboRivierengebied.BackColor = Color.LightGreen;
                    cboRivierengebied.Text = curImageInfo.Rivierengebied;
                    cboTechniek.BackColor = Color.LightGreen;
                    cboTechniek.Text = curImageInfo.Techniek;
                }
                // Resize dataview
                dataGridViewMetaData.AutoResizeColumns();
            }
        }

        private void TryToSetArchiveAndSubNr(string inputString)
        {
            try
            {
                string regexArchiveNr = "([0-9]*)-([0-9]*)";

                RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);

                Regex regArchiveNr = new Regex(regexArchiveNr, options);
                Match matchArchiveNr = regArchiveNr.Match(inputString);

                int intArchiveNr = 0;
                int intSubNr = 0;

                if (matchArchiveNr.Success)
                {
                    intArchiveNr = Convert.ToInt32(matchArchiveNr.Groups[1].Value);
                    intSubNr = Convert.ToInt32(matchArchiveNr.Groups[2].Value);
                    textBoxArchiefnummer.Text = intArchiveNr.ToString();
                    textBoxSubnummer.Text = intSubNr.ToString();
                }
            }
            catch
            {
            }
        }

        private void ShowTypeTab()
        {
            if (comboBoxObjectType.Text.StartsWith("Foto"))
                tabControlArchief.SelectTab(0);
            else
                tabControlArchief.SelectTab(1);
        }

        private void comboBoxObjectType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowTypeTab();
        }

        private static Nullable<DateTime> GetImageDate(Image image)
        {
            int tagIndex = -1;

            Nullable<DateTime> date = null;

            // find the index of the id we're looking for 
            // Note: the Exif specification at http://exif.org specifies 0x9003 for 
            // the date/time the image was taken 
            for (int i = 0; i < image.PropertyIdList.Length; i++)
            {
                if (image.PropertyIdList[i] == Int32.Parse("9003", NumberStyles.HexNumber))
                {
                    tagIndex = i;
                    break;
                }
            }

            // return if the tag is not found 
            if (tagIndex < 0) return null;

            // parse the date string which is in the format: yyyy:mm:dd hh:mm:ss 
            string dateString = null;

            try
            {
                PropertyItem item = image.PropertyItems[tagIndex];
                dateString = ASCIIEncoding.ASCII.GetString(item.Value);

                string[] dParts = dateString.Split(new string[] { ":", " " }, StringSplitOptions.RemoveEmptyEntries);
                int year = Convert.ToInt32(dParts[0].Trim());
                int month = Convert.ToInt32(dParts[1].Trim());
                int day = Convert.ToInt32(dParts[2].Trim());
                int hour = Convert.ToInt32(dParts[3].Trim());
                int minute = Convert.ToInt32(dParts[4].Trim());
                int second = Convert.ToInt32(dParts[5].Trim());

                date = new DateTime(year, month, day, hour, minute, second);

            }
            catch { }
            // in case of an exception, we'll just ignore it and not return a date 

            return date;
        }

        private static string GetImageExifString(Image image, string hexCode)
        {
            int tagIndex = -1;

            // find the index of the id we're looking for 
            // Note: the Exif specification at http://exif.org specifies 0x9003 for 
            // the date/time the image was taken 
            for (int i = 0; i < image.PropertyIdList.Length; i++)
            {
                if (image.PropertyIdList[i] == Int32.Parse(hexCode, NumberStyles.HexNumber))
                {
                    tagIndex = i;
                    break;
                }
            }

            // return if the tag is not found 
            if (tagIndex < 0) return null;

            PropertyItem item = image.PropertyItems[tagIndex];
            return ASCIIEncoding.ASCII.GetString(item.Value);
        }

        private void GetMetaData(string imageFileName)
        {
            try
            {
                ImageFile file = ImageFile.FromFile(imageFileName);
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("Naam");
                dt.Columns.Add("Waarde");

                // Read metadata
                foreach (ExifProperty item in file.Properties.Values)
                {
                    System.Data.DataRow dr = dt.NewRow();
                    dr["Naam"] = item.Name;
                    dr["Waarde"] = item.Value;
                    dt.Rows.Add(dr);
                }
                dataGridViewMetaData.DataSource = dt;

                buttonExifDatum.Enabled = true;
                buttonExifOmschrijving.Enabled = true;
                buttonExifTitel.Enabled = true;
            }
            catch (Exception exc)
            {
                statusBar.Text = exc.Message;
            }
        }

        private void bewaarMetadataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rowindex >= 0)
            {
                ImageInfo curImageInfo = new ImageInfo();

                bool dataOk = true;
                try
                {
                    if (textBoxTitel.Text.Length > 0)
                        curImageInfo.Titel = textBoxTitel.Text;
                    else
                        dataOk = false;

                    if (textBoxOmschrijving.Text.Length > 0)
                        curImageInfo.Description = textBoxOmschrijving.Text;
                    else
                        dataOk = false;

                    // Optional fields
                    curImageInfo.Lokatie = textBoxLokatie.Text;
                    curImageInfo.Vervaardiger = textBoxVervaardiger.Text;
                    curImageInfo.Type = comboBoxObjectType.SelectedItem.ToString();
                    curImageInfo.Techniek = cboTechniek.Text;
                    curImageInfo.Rivierengebied = cboRivierengebied.Text;
                    curImageInfo.Provincie = cboProvincie.Text;
                    curImageInfo.Project = cboProject.Text;

                    if (curImageInfo.Type == "Video")
                    {
                        curImageInfo.Montage = comboBoxMontage.SelectedItem.ToString();
                        if (textBoxCollectie.Text.Length > 0)
                            curImageInfo.Collectie = textBoxCollectie.Text;
                        else
                            dataOk = false;

                        // Defaults
                        curImageInfo.Archiefnummer = "";
                        curImageInfo.Subnummer = "";
                        curImageInfo.Mapnummer = "";
                    }
                    else
                    {
                        curImageInfo.Archiefnummer = textBoxArchiefnummer.Text;
                        curImageInfo.Subnummer = textBoxSubnummer.Text;
                        curImageInfo.Mapnummer = textBoxMapnummer.Text;

                        // Defaults
                        curImageInfo.Collectie = "";
                        curImageInfo.Montage = comboBoxMontage.SelectedItem.ToString();
                    }
                    curImageInfo.Datum = Convert.ToDateTime(dateTimePickerDatum.Text);

                }
                catch (Exception exc)
                {
                    dataOk = false;
                    statusBar.Text = curImageInfo.Titel + "-" + exc.Message;
                }

                if (dataOk)
                {
                    SaveXml(curFileName.Substring(0, curFileName.LastIndexOf(".")) + ".xml", curImageInfo);
                    FetchRow();
                }
            }
        }

        public string GetXml(ImageInfo curImageInfo)
        {
            string returnString = "";
            returnString += "<xml>";
            returnString += "<type>" + curImageInfo.Type + "</type>";
            returnString += "<titel><![CDATA[" + curImageInfo.Titel + "]]></titel>";
            returnString += "<description><![CDATA[" + curImageInfo.Description + "]]></description>";
            returnString += "<datum>" + curImageInfo.Datum + "</datum>";
            returnString += "<archiefnummer>" + curImageInfo.Archiefnummer + "</archiefnummer>";
            returnString += "<subnummer>" + curImageInfo.Subnummer + "</subnummer>";
            returnString += "<mapnummer>" + curImageInfo.Mapnummer + "</mapnummer>";
            returnString += "<montage>" + curImageInfo.Montage + "</montage>";
            returnString += "<collectie>" + curImageInfo.Collectie + "</collectie>";
            returnString += "<lokatie>" + curImageInfo.Lokatie + "</lokatie>";
            returnString += "<vervaardiger>" + curImageInfo.Vervaardiger + "</vervaardiger>";
            returnString += "<techniek>" + curImageInfo.Techniek + "</techniek>";
            returnString += "<rivierengebied>" + curImageInfo.Rivierengebied + "</rivierengebied>";
            returnString += "<provincie>" + curImageInfo.Provincie + "</provincie>";
            returnString += "<project>" + curImageInfo.Project + "</project>";
            returnString += "</xml>";
            return returnString;
        }

        public void SaveXml(string fileLocation, ImageInfo curImageInfo)
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

            xmlDoc.LoadXml(GetXml(curImageInfo));
            xmlDoc.Save(fileLocation);
            xmlDoc = null;
        }

        public ImageInfo LoadXml(string fileName)
        {
            ImageInfo curImageInfo = new ImageInfo();
            curImageInfo.Type = "Leeg";

            // Convert filename to correct extension
            fileName = fileName.Substring(0, fileName.LastIndexOf(".")) + ".xml";

            if (System.IO.File.Exists(fileName))
            {
                try
                {
                    System.Xml.XmlDocument xmlFile = new XmlDocument();
                    xmlFile.Load(fileName);

                    curImageInfo.Type = xmlFile.SelectSingleNode("/xml/type/text()").Value.ToString();

                    curImageInfo.Titel = xmlFile.SelectSingleNode("/xml/titel/text()").Value.ToString();
                    curImageInfo.Description = xmlFile.SelectSingleNode("/xml/description/text()").Value.ToString();
                    curImageInfo.Datum = Convert.ToDateTime(xmlFile.SelectSingleNode("/xml/datum/text()").Value);
                    if (xmlFile.SelectSingleNode("/xml/archiefnummer/text()") != null)
                        curImageInfo.Archiefnummer = xmlFile.SelectSingleNode("/xml/archiefnummer/text()").Value.ToString();
                    else
                        curImageInfo.Archiefnummer = "";
                    if (xmlFile.SelectSingleNode("/xml/subnummer/text()") != null)
                        curImageInfo.Subnummer = xmlFile.SelectSingleNode("/xml/subnummer/text()").Value.ToString();
                    else
                        curImageInfo.Subnummer = "";
                    if (xmlFile.SelectSingleNode("/xml/mapnummer/text()") != null)
                        curImageInfo.Mapnummer = xmlFile.SelectSingleNode("/xml/mapnummer/text()").Value.ToString();
                    else
                        curImageInfo.Mapnummer = "";
                    if (xmlFile.SelectSingleNode("/xml/montage/text()") != null)
                        curImageInfo.Montage = xmlFile.SelectSingleNode("/xml/montage/text()").Value.ToString();
                    else
                        curImageInfo.Montage = "";
                    if (xmlFile.SelectSingleNode("/xml/collectie/text()") != null)
                        curImageInfo.Collectie = xmlFile.SelectSingleNode("/xml/collectie/text()").Value.ToString();
                    else
                        curImageInfo.Collectie = "";
                    if (xmlFile.SelectSingleNode("/xml/lokatie/text()") != null)
                        curImageInfo.Lokatie = xmlFile.SelectSingleNode("/xml/lokatie/text()").Value.ToString();
                    else
                        curImageInfo.Lokatie = "";
                    if (xmlFile.SelectSingleNode("/xml/vervaardiger/text()") != null)
                        curImageInfo.Vervaardiger = xmlFile.SelectSingleNode("/xml/vervaardiger/text()").Value.ToString();
                    else
                        curImageInfo.Vervaardiger = "";
                    if (xmlFile.SelectSingleNode("/xml/provincie/text()") != null)
                        curImageInfo.Provincie = xmlFile.SelectSingleNode("/xml/provincie/text()").Value.ToString();
                    else
                        curImageInfo.Provincie = "";
                    if (xmlFile.SelectSingleNode("/xml/project/text()") != null)
                        curImageInfo.Project = xmlFile.SelectSingleNode("/xml/project/text()").Value.ToString();
                    else
                        curImageInfo.Project = "";
                    if (xmlFile.SelectSingleNode("/xml/rivierengebied/text()") != null)
                        curImageInfo.Rivierengebied = xmlFile.SelectSingleNode("/xml/rivierengebied/text()").Value.ToString();
                    else
                        curImageInfo.Rivierengebied = "";
                    if (xmlFile.SelectSingleNode("/xml/techniek/text()") != null)
                        curImageInfo.Techniek = xmlFile.SelectSingleNode("/xml/techniek/text()").Value.ToString();
                    else
                        curImageInfo.Techniek = "";

                    return curImageInfo;
                }
                catch (Exception exc)
                {
                    statusBar.Text = "Inlezen - " + fileName + "-" + exc.Message;
                    return curImageInfo;
                }
            }
            else
            {
                return curImageInfo;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            bewaarMetadataToolStripMenuItem_Click(sender, e);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            tabMediaBeschrijver.SelectTab(1);
        }

        private string GenerateString()
        {
            string tempString = "";

            ImageFile file = ImageFile.FromFile(curFileName);

            // Read metadata
            foreach (ExifProperty item in file.Properties.Values)
            {
                if (item.Name == ExifTag.ImageDescription.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
                if (item.Name == ExifTag.WindowsTitle.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
                if (item.Name == ExifTag.WindowsComment.ToString())
                {
                    tempString = tempString + " - " + item.Value.ToString();
                }
                if (item.Name == ExifTag.WindowsKeywords.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
                if (item.Name == ExifTag.WindowsSubject.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
                if (item.Name == ExifTag.MakerNote.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
                if (item.Name == ExifTag.UserComment.ToString())
                {
                    tempString = tempString + " " + item.Value.ToString();
                }
            }
            tempString = tempString.Replace("  ", " ");
            tempString = tempString.Replace("System.Byte[]", "");

            // Ad hoc modifications
            if (textBoxSource1.Text != "")
                tempString = tempString.Replace(textBoxSource1.Text, textBoxDest1.Text);
            if (textBoxSource2.Text != "")
                tempString = tempString.Replace(textBoxSource2.Text, textBoxDest2.Text);
            if (textBoxSource3.Text != "")
                tempString = tempString.Replace(textBoxSource3.Text, textBoxDest3.Text);
            if (textBoxSource4.Text != "")
                tempString = tempString.Replace(textBoxSource4.Text, textBoxDest4.Text);
            if (textBoxSource5.Text != "")
                tempString = tempString.Replace(textBoxSource5.Text, textBoxDest5.Text);
            if (textBoxSource6.Text != "")
                tempString = tempString.Replace(textBoxSource6.Text, textBoxDest6.Text);
            if (textBoxSource7.Text != "")
                tempString = tempString.Replace(textBoxSource7.Text, textBoxDest7.Text);

            return tempString.Trim();
        }

        private void buttonTitelEXIF_Click(object sender, EventArgs e)
        {
            textBoxTitel.Text = GenerateString();
        }

        private void buttonOmschrijvingEXIF_Click(object sender, EventArgs e)
        {
            textBoxOmschrijving.Text = GenerateString();
        }

        #region Save
        private void buttonSave_Click(object sender, EventArgs e)
        {
            bewaarMetadataToolStripMenuItem_Click(sender, e);
        }
        private void btnToolbarSave_Click(object sender, EventArgs e)
        {
            bewaarMetadataToolStripMenuItem_Click(sender, e);
        }
        private void btnToolbarSaveAndNext_Click(object sender, EventArgs e)
        {
            bewaarMetadataToolStripMenuItem_Click(sender, e);
            try
            {
                rowindex++;
                dataGridViewImages.FirstDisplayedScrollingRowIndex = dataGridViewImages.Rows[rowindex].Index;
                dataGridViewImages.Refresh();
                dataGridViewImages.CurrentCell = dataGridViewImages.Rows[rowindex].Cells[0];
                dataGridViewImages.Rows[rowindex].Selected = true;
                FetchRow();
            }
            catch (Exception exc)
            {
                statusBar.Text = exc.Message;

                rowindex = 0;
                dataGridViewImages.FirstDisplayedScrollingRowIndex = dataGridViewImages.Rows[rowindex].Index;
                dataGridViewImages.Refresh();
                dataGridViewImages.CurrentCell = dataGridViewImages.Rows[rowindex].Cells[0];
                dataGridViewImages.Rows[rowindex].Selected = true;
                FetchRow();
            }
        }
        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            dateTimePickerDatum.Text = GetImageDate(pictureBoxImage.Image).ToString();
        }

        private void dataGridViewImages_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
            rowindex = e.RowIndex;
            FetchRow();
        }

        private void SelectDirectory_Click(object sender, EventArgs e)
        {
            DirSelector.SelectedPath = textBoxBaseDir.Text;
            DirSelector.ShowNewFolderButton = false;
            if (DirSelector.ShowDialog() == DialogResult.OK)
            {
                textBoxBaseDir.Text = DirSelector.SelectedPath;

                // Open App.Config of executable
                System.Configuration.Configuration config =
                  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.AppSettings.Settings.Remove("defaultDirectory");
                config.AppSettings.Settings.Add("defaultDirectory", textBoxBaseDir.Text);

                // Save the configuration file.
                config.Save(ConfigurationSaveMode.Modified);

                // Force a reload of a changed section.
                ConfigurationManager.RefreshSection("appSettings");

            }
            tabMediaBeschrijver.SelectTab(0);
            LoadDirectory();
        }

        private void buttonMoveSplit_Click(object sender, EventArgs e)
        {
            if (splitContainer1.SplitterDistance < 1118)
            {
                splitContainer1.SplitterDistance = 1138;
                buttonMoveSplit.Image = buttonLeft.Image;
                dataGridViewMetaData.AutoResizeColumns();
            }
            else
            {
                splitContainer1.SplitterDistance = 708;
                buttonMoveSplit.Image = buttonRight.Image;
                dataGridViewMetaData.AutoResizeColumns();
            }
        }

        private void btnToolbarSaveAll_Click(object sender, EventArgs e)
        {
            for (int rowindex = 0; rowindex < dataGridViewImages.RowCount; rowindex++)
            {
                curFileName = dataGridViewImages.Rows[rowindex].Cells["Filenaam"].Value.ToString();

                ImageInfo curImageInfo = new ImageInfo();

                bool dataOk = true;
                try
                {
                    if (textBoxTitel.Text.Length > 0)
                        curImageInfo.Titel = textBoxTitel.Text;
                    else
                        dataOk = false;

                    if (textBoxOmschrijving.Text.Length > 0)
                        curImageInfo.Description = textBoxOmschrijving.Text;
                    else
                        dataOk = false;

                    // Optional fields
                    curImageInfo.Lokatie = textBoxLokatie.Text;
                    curImageInfo.Vervaardiger = textBoxVervaardiger.Text;
                    curImageInfo.Type = comboBoxObjectType.SelectedItem.ToString();
                    if (curImageInfo.Type == "Video")
                    {
                        curImageInfo.Montage = comboBoxMontage.SelectedItem.ToString();
                        if (textBoxCollectie.Text.Length > 0)
                            curImageInfo.Collectie = textBoxCollectie.Text;
                        else
                            dataOk = false;

                        // Defaults
                        curImageInfo.Archiefnummer = "";
                        curImageInfo.Subnummer = "";
                        curImageInfo.Mapnummer = "";
                    }
                    else
                    {
                        curImageInfo.Archiefnummer = textBoxArchiefnummer.Text;
                        curImageInfo.Subnummer = textBoxSubnummer.Text;
                        curImageInfo.Mapnummer = textBoxMapnummer.Text;

                        curImageInfo.Techniek = cboTechniek.Text;
                        curImageInfo.Rivierengebied = cboRivierengebied.Text;
                        curImageInfo.Provincie = cboProvincie.Text;
                        curImageInfo.Project = cboProject.Text;

                        // Defaults
                        curImageInfo.Collectie = "";
                        curImageInfo.Montage = comboBoxMontage.SelectedItem.ToString();
                    }
                    curImageInfo.Datum = Convert.ToDateTime(dateTimePickerDatum.Text);

                    // If no record already exists
                    if ((dataOk) && !File.Exists(curFileName.Substring(0, curFileName.LastIndexOf(".")) + ".xml"))
                        SaveXml(curFileName.Substring(0, curFileName.LastIndexOf(".")) + ".xml", curImageInfo);

                }
                catch (Exception exc)
                {
                    dataOk = false;
                    statusBar.Text = curImageInfo.Titel + "-" + exc.Message;
                }
            }
            FetchRow();
        }

        private void buttonDatumOnbekend_Click(object sender, EventArgs e)
        {
            dateTimePickerDatum.Text = "01-01-1900";
        }

        private void btnToolbarDeleteAll_Click(object sender, EventArgs e)
        {
            for (int rowindex = 0; rowindex < dataGridViewImages.RowCount; rowindex++)
            {
                curFileName = dataGridViewImages.Rows[rowindex].Cells["Filenaam"].Value.ToString();

                if (File.Exists(curFileName.Substring(0, curFileName.LastIndexOf(".")) + ".xml"))
                    File.Delete(curFileName.Substring(0, curFileName.LastIndexOf(".")) + ".xml");
            }
            FetchRow();
        }

        private void checkBoxVideoProcessing_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxVideoProcessing.Checked)
            {
                btnGenerateVideo.Enabled = true;
            }
            else
            {
                btnGenerateVideo.Enabled = false;
            }
        }

        public string SetMovieFormat()
        {
            if (radioButton4x3.Checked)
                return "400x300";
            else
                return "400x225";
        }

        private void btnGenerateVideo_Click(object sender, EventArgs e)
        {
            string selPath = textBoxBaseDir.Text;

            FileStream fs = new FileStream(textBoxBaseDir.Text + "/createmovies.bat", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            // Write to the file using StreamWriter class 
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

            bool workToDo = false;

            string pathToFFMPEG = "";
            if (Application.ExecutablePath.ToLower().Contains("jmediabeschrijver.exe"))
                 pathToFFMPEG = Application.ExecutablePath.ToLower().Replace("jmediabeschrijver.exe", "ffmpeg.exe");

            string[] directoryList = System.IO.Directory.GetFiles(selPath, "*.*");
            string extension = "";
            foreach (string inputFileName in directoryList)
            {
                string videoFile = inputFileName.ToLower();
                if (videoFile.Contains(".mpeg") ||
                    videoFile.Contains(".mpg") ||
                    videoFile.Contains(".mov") ||
                    videoFile.Contains(".m4v") ||
                    videoFile.Contains(".mp4") ||
                    videoFile.Contains(".wmv") ||
                    videoFile.Contains(".flv"))
                {
                    // Allowed formats found 

                    if (checkBoxSrc.Checked)
                        extension = textBoxBron.Text;
                    else
                        if (videoFile.Contains(".mpeg"))
                            extension = "mpeg";
                        else
                            if (videoFile.Contains(".mpg"))
                                extension = "mpg";
                            else
                                if (videoFile.Contains(".mov"))
                                    extension = "mov";
                                else
                                    if (videoFile.Contains(".m4v"))
                                        extension = "m4v";
                                    else
                                        if (videoFile.Contains(".mp4"))
                                            extension = "mp4";
                                        else
                                            if (videoFile.Contains(".wmv"))
                                                extension = "wmv";
                                            else
                                                if (videoFile.Contains(".flv"))
                                                    extension = "flv";

                    if (checkBoxFLV.Checked)
                    {
                        string FileNameFLV = videoFile.Replace(extension, "flv");
                        if (!FileNameFLV.Equals(videoFile))
                            if (!System.IO.File.Exists(FileNameFLV) || (System.IO.File.Exists(FileNameFLV) && checkBoxOverwrite.Checked))
                            {
                                if (checkBoxOverwrite.Checked) System.IO.File.Delete(FileNameFLV);
                                try
                                {
                                    m_streamWriter.WriteLine("{0}", pathToFFMPEG + " -i \"" + videoFile + "\" -s " + SetMovieFormat() + " -b 280000 -ar 44100 -ab 56000 -ac 1 -r 25 -f flv -y \"" + FileNameFLV + "\"");
                                    workToDo = true;
                                }
                                catch
                                {
                                }
                            }
                    }
                    if (checkBoxWMV.Checked)
                    {
                        string FileNameWMV = videoFile.Replace(extension, "wmv");
                        if (!FileNameWMV.Equals(videoFile))
                            if (!System.IO.File.Exists(FileNameWMV) || (System.IO.File.Exists(FileNameWMV) && checkBoxOverwrite.Checked))
                            {
                                if (checkBoxOverwrite.Checked) System.IO.File.Delete(FileNameWMV);
                                try
                                {
                                    m_streamWriter.WriteLine("{0}", pathToFFMPEG + " -i \"" + videoFile + "\" -s " + SetMovieFormat() + " -vcodec wmv2 -b 1904000 -ar 44100 -ab 380000 -ac 1 -r 25 -y \"" + FileNameWMV + "\"");
                                    workToDo = true;
                                }
                                catch
                                {
                                }
                            }
                    }
                    if (checkBox3GP.Checked)
                    {
                        string FileName3GP = videoFile.Replace(extension, "3gp");
                        if (!FileName3GP.Equals(videoFile))
                            if (!System.IO.File.Exists(FileName3GP) || (System.IO.File.Exists(FileName3GP) && checkBoxOverwrite.Checked))
                            {
                                if (checkBoxOverwrite.Checked) System.IO.File.Delete(FileName3GP);
                                try
                                {
                                    //-s qcif = 176x144
                                    m_streamWriter.WriteLine("{0}", pathToFFMPEG + " -i \"" + videoFile + "\" -s qcif -vcodec h263 -acodec aac -strict experimental -ab 128k -b 45000 -ac 1 -r 15 -f 3gp -y \"" + FileName3GP + "\"");
                                    workToDo = true;
                                }
                                catch
                                {
                                }
                            }
                    }
                    if (checkBoxMP4.Checked)
                    {
                        string FileNameMP4 = videoFile.Replace(extension, "mp4");
                        if (!FileNameMP4.Equals(videoFile))
                            if (!System.IO.File.Exists(FileNameMP4) || (System.IO.File.Exists(FileNameMP4) && checkBoxOverwrite.Checked))
                            {
                                if (checkBoxOverwrite.Checked) System.IO.File.Delete(FileNameMP4);
                                try
                                {
                                    m_streamWriter.WriteLine("{0}", pathToFFMPEG + " -i \"" + videoFile + "\" -s " + SetMovieFormat() + " -vcodec libx264 -b 280000 -ar 44100 -ab 56000 -ac 1 -r 25 -f mp4 -y \"" + FileNameMP4 + "\"");
                                    workToDo = true;
                                }
                                catch
                                {
                                }
                            }
                    }
                }
            }

            if (checkBoxJPG.Checked)
            {
                if (checkBoxSrc.Checked)
                {
                    directoryList = System.IO.Directory.GetFiles(selPath, "*." + textBoxBron.Text);
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, "." + textBoxBron.Text, m_streamWriter);
                        workToDo = true;
                    }
                }
                else
                {
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.mp4");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".mp4", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.mpg");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".mpg", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.mpeg");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".mpeg", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.mov");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".mov", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.m4v");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".m4v", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.wmv");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".wmv", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.f4v");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".f4v", m_streamWriter);
                        workToDo = true;
                    }
                    directoryList = System.IO.Directory.GetFiles(selPath, "*.flv");
                    foreach (string imageFile in directoryList)
                    {
                        GenerateImage(imageFile, ".flv", m_streamWriter);
                        workToDo = true;
                    }
                }
            }

            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();

            if (workToDo)
            {
                //Start a new process.
                System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(textBoxBaseDir.Text + "\\createmovies.bat");
                // Wait until it ends.
                myProcess.WaitForExit();
                //Close the process to free resources.
                myProcess.Close();
            }
            // cleanup file
            System.IO.File.Delete(textBoxBaseDir.Text + "\\createmovies.bat");

            tabMediaBeschrijver.SelectTab(0);
            LoadDirectory();
        }

        private void GenerateImage(string imageFile, string extension, StreamWriter m_streamWriter)
        {
            string FileNameJPG = imageFile.ToLower().Replace(extension, ".jpg");
            if (!System.IO.File.Exists(FileNameJPG))
            {
                try
                {
                    if (Application.ExecutablePath.ToLower().Contains("jmediabeschrijver.exe"))
                        m_streamWriter.WriteLine("{0}", Application.ExecutablePath.ToLower().Replace("jmediabeschrijver.exe", "ffmpeg.exe") + " -i \"" + imageFile + "\" -y -r 1 -ss " + txtBoxTimInMovie.Text + " -vframes 1 -f image2 \"" + FileNameJPG + "\"");
                }
                catch
                {
                }
            }
        }

    }
}
